package com.voice.call.controller;

import java.io.File;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.voice.call.common.Const;
import com.voice.call.common.ConstLang;
import com.voice.call.common.ConstUtil;
import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.entity.UserInfo;
import com.voice.call.service.ConsumeLogService;
import com.voice.call.service.UserInfoService;
import com.voice.call.utils.IpUtil;
import com.voice.call.utils.JSONUtil;
import com.voice.call.utils.StringUtil;
import com.voice.call.version.ApiVersion;

//用户管理
@RestController
@RequestMapping("/api/{version}/user/")
public class UserInfoController {
	
	private final Logger log = LoggerFactory.getLogger(UserInfoController.class);
	
	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	private ConsumeLogService consumeLogService;
	
	@Resource
	private Properties configProperties;
	
	//自动登录
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "autoLogin", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result autoLogin(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("xaid") == null || params.get("mac") == null) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		String v = ConstUtil.getVersionName(params);
		//String vcode = params.get("code").toString();
		UserInfo user = JSONUtil.mapToObject(params, UserInfo.class);
		String ip = IpUtil.getIpAddr(request);
		user.setIp(ip);
		Result rs = userInfoService.autoLogin(user,"",v);
		rs.changeLange(lang);
		return rs;
	}
	
	
	//facebook登录
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "fbLogin", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result userLogin(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("phone") == null  || params.get("fbId") == null || params.get("name") == null || params.get("photo") == null) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		//String vcode = params.get("code").toString();
		UserInfo user = JSONUtil.mapToObject(params, UserInfo.class);
		String ip = IpUtil.getIpAddr(request);
		user.setIp(ip);
		String v = ConstUtil.getVersionName(params);
		Result rs = userInfoService.userFbLogin(user,null,v,"fb_login");
		rs.changeLange(lang);
		return rs;
	}
	
	
	//手机号+验证码 登录
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "smsLogin", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result smsLogin(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("phone") == null  || params.get("vcode") == null || StringUtil.isEmpty(params.get("vcode").toString().trim())) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		
		String vcode = params.get("vcode").toString().trim();
		
		UserInfo user = JSONUtil.mapToObject(params, UserInfo.class);
		String ip = IpUtil.getIpAddr(request);
		user.setIp(ip);
		String v=ConstUtil.getVersionName(params);
		Result rs = userInfoService.userSMSLogin(user, vcode,v);
		rs.changeLange(lang);
		return rs;
	}
	
	//帐号登录
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "accountLogin", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result accountLogin(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("phone") == null || params.get("password") == null) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		String phone = params.get("phone").toString();
		String password = params.get("password").toString();
		String ip = IpUtil.getIpAddr(request);
		String v=ConstUtil.getVersionName(params);
		String xaid= "";
		if (params.get("xaid")!=null) {
			xaid=params.get("xaid").toString();
		}
		String mac= "";
		if (params.get("mac")!=null) {
			mac=params.get("mac").toString();
		}
		
		Result rs = userInfoService.userAccountLogin(phone, password,ip,v,xaid,mac);
		rs.changeLange(lang);
		return rs;
	}
	
	//设置密码
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "settingPassword", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result settingpassword(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("uid") == null || params.get("uid").toString().equals("0") || params.get("password") == null) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		
       Integer user_id = Integer.valueOf(params.get("uid").toString());
       String password = params.get("password").toString();
       
       Result rs = userInfoService.settingPassword(user_id, password);
       rs.changeLange(lang);
        return rs;
	}
	
	//绑定手机
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "bindPhone", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result bindPhone(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("uid") == null || params.get("uid").toString().equals("0") || params.get("phone") == null || params.get("vcode") == null) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		Integer user_id = Integer.valueOf(params.get("uid").toString());
		 String phone = params.get("phone").toString();
		 String vcode = params.get("vcode").toString();
		 String ip = IpUtil.getIpAddr(request);
		 
		 String xaid= "";
		if (params.get("xaid")!=null) {
			xaid=params.get("xaid").toString();
		}
		String mac= "";
		if (params.get("mac")!=null) {
			mac=params.get("mac").toString();
		}
		 
		 Result rs = userInfoService.bindPhone(user_id, phone,vcode,ip,xaid,mac);
		 rs.changeLange(lang);
		return  rs;
	}
	
	//用户是否存在
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "exists", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result existsUser(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		//log.debug("参数:{}",JSONUtil.objectToJson(params));
		String lang = ConstLang.getLang(params);
		// 判断入参
		if (null == params || params.get("phone") == null) {
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		String phone = params.get("phone").toString();
		
		Result rs = userInfoService.existsUser(phone);
		rs.changeLange(lang);
        return rs;
	}
	
	//当日积分获取是否 已经达到上限
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "integralLimit", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result userIntegralLimit(HttpServletRequest request,@RequestBody Map<String, Object> params){
		String lang = ConstLang.getLang(params);
		try {
			
			//log.debug("参数:{}",JSONUtil.objectToJson(params));
			// 判断入参
			if (null == params || params.get("uid") == null) {
				//log.error(ResultEnum.PARAM_ERROR.getMsg());
				return new Result(ResultEnum.PARAM_ERROR);
			}
			
			Integer user_id = Integer.valueOf(params.get("uid").toString());
			if (consumeLogService.hasOverMaxIntegralLimit(user_id)) {
				return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR,lang);
			}
	        return new Result(ResultEnum.SUCCESS,lang);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(ResultEnum.SYSTEM_ERROR,lang);
		}
		
		
	}
	
	//查询帐户
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "query", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result queryUser(HttpServletRequest request,@RequestBody Map<String, Object> params){
		
		try {
			
			//log.debug("参数:{}",JSONUtil.objectToJson(params));
			String lang = ConstLang.getLang(params);
			// 判断入参
			if (null == params || params.get("xaid") == null || params.get("mac") == null) {
				//log.error(ResultEnum.PARAM_ERROR.getMsg());
				return new Result(ResultEnum.PARAM_ERROR,lang);
			}
			String xaid = params.get("xaid").toString();
			String mac = params.get("mac").toString();
			
			Result rs = userInfoService.queryUserForXaidMac(xaid, mac);
			rs.changeLange(lang);
	        return rs;
			
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(ResultEnum.SYSTEM_ERROR,ConstLang.getLang(params));
		}
		
		
	}
	
	//修改用户信息
	@ResponseBody
	@ApiVersion(1)
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = Const.JSON_UTF8)
	public Result editUser(HttpServletRequest request,@RequestParam(value = "file", required = false) MultipartFile file){
		
       String lang = Const.LANGUAGE;
       if (request.getParameter("lang")!=null) {
    	   
    	   if(ConstLang.langArr.contains(request.getParameter("lang").toString())){
    		   lang = request.getParameter("lang");
    	   }
		
	   }
		if(request.getParameter("uid")==null || request.getParameter("token")==null){
			//log.error(ResultEnum.PARAM_ERROR.getMsg());
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		
		if (request.getParameter("name")==null && file==null) {
			return new Result(ResultEnum.PARAM_ERROR,lang);
		}
		Integer uid = Integer.valueOf(request.getParameter("uid"));
		String token = request.getParameter("token");
		UserInfo user = null;
	        if(userInfoService!=null){
	        	user = userInfoService.getUserForId(Integer.valueOf(uid));
	        }	
	        if(user == null){
	        	return new Result(ResultEnum.USER_ILLEGAL,lang);
	        }
	        
	        if (!token.equals(user.getToken())) {
				return new Result(ResultEnum.TOKEN_INVALID,lang);
			}
	        Date nowDate = new Date();

	        if(user.getTokenExpired().compareTo(nowDate) < 0){
	        	return new Result(ResultEnum.TOKEN_EXPRIED,lang);
	        }
	        //log.info("验证sign成功");
		
		
		
		UserInfo entity = new UserInfo();
		entity.setId(uid);
		// 判断入参
       if(file!=null){
			
			String imgUrl = configProperties.getProperty(Const.UPLOAD_HTTP)+file.getOriginalFilename();
			String path = configProperties.getProperty(Const.UPLOAD_SAVE_PATH);
			try {
				
				File targetFile = new File(path, file.getOriginalFilename());
				//判断文件夹是否已经存在，如果已经存在了重新建   
				if (!targetFile.exists()) {   
				    targetFile.mkdirs();   
				}
				//转存文件
				file.transferTo(targetFile);
				
				entity.setPhoto(imgUrl);
				//entity.setImagePic(imgUrl);
				
			} catch (Exception e) {
				e.printStackTrace();
				//log.error("保存文件失败");
			}
			
			
		}
       
       String nick = "";
       if (request.getParameter("name")!=null) {
    	   nick = request.getParameter("name");
	   }
       if (!StringUtil.isEmpty(nick)) {
    	   entity.setName(nick);
	   }
       entity.setMtime(new Date());
       
       Result rs = userInfoService.editUser(entity);
       rs.changeLange(lang);
	   return rs;
		
	}
	

}
